﻿using FlyingEye.Consts;
using FlyingEye.Devices;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace FlyingEye.EntityFrameworkCore
{
    public class DeviceAppServiceDbContext : AbpDbContext<DeviceAppServiceDbContext>
    {
        public DeviceAppServiceDbContext(DbContextOptions<DeviceAppServiceDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<DeviceConfigurationModel>(builder =>
            {
                builder.ToTable(DeviceAppServiceDbConsts.DbTablePrefix + "DeviceConfigurations", DeviceAppServiceDbConsts.DbSchema);

                // 一个设备主机资源下，不能配置重复的 ip 和 端口
                builder.HasIndex(e => new { ResourceId = e.ResourceId, IPAddress = e.IPAddress, Port = e.Port })
                .IsUnique();

                // 一个设备资源号下，不能配置重复的设备逻辑名
                builder.HasIndex(e => new { ResourceId = e.ResourceId, DeviceName = e.DeviceName })
                .IsUnique();
            });

            // 配置无需导航到主体实体的一对多
            modelBuilder.Entity<DeviceClientModel>(builder =>
            {
                builder.ToTable(DeviceAppServiceDbConsts.DbTablePrefix + "DeviceClients", DeviceAppServiceDbConsts.DbSchema);

                builder.HasMany<DeviceConfigurationModel>(e => e.DeviceConfigurations)
                .WithOne()
                .HasForeignKey(e => e.ResourceId)
                .IsRequired();
            });

            base.OnModelCreating(modelBuilder);
        }
    }
}
